<script lang="ts" setup name="AddFun">
import type { Ref } from 'vue'
import { nextTick, ref } from 'vue'
import { CirclePlus, Delete, Search } from '@element-plus/icons-vue'
import { _ } from 'iking-utils'
import type { FormInstance } from 'element-plus'
import type { addTableForm } from '../interface'
import DatasourceModal from './../../../system-manage/datasource-manage/DatasourceModal.vue'
import {
  addTableDefinition,
  allDatasource
} from '@/MainApp/apis/manage-design'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  }
})
// const emits = defineEmits<{
//   (event: 'cancel'): void
//   (event: 'update:visible', value: boolean): void
//   (event: 'confirm'): void
// }>()

const { msgBoxWarning, msgError } = useMessage()
const { lenContent, lenName } = useLength()
const { t } = useConfig()
const projectData: Ref<any> | undefined = inject('projectData')

const formKey = {
  name: '',
  packageName: '',
  description: '',
  datasourceType: 'DATABASE',
  datasourceId: '',
  projectName: '',
  projectPackageName: '',
  projectId: ''
}
const projectFormRef = ref()
const projectForm = ref({ ...formKey })

const dataBase = ref<Array<any>>([])

if (projectData && projectData?.value?.goFun === 'fun') {
  projectForm.value.projectId = projectData?.value?.projectId
  projectForm.value.projectName = projectData?.value?.name
  projectForm.value.projectPackageName = projectData?.value?.projectPackageName
}

const selectVisible = ref(false)
const selectTable = ref<Array<any>>([])
const datasourceList = ref<Array<any>>([])
const addTableVisible = ref(false)
const selectTableStr = ref('')
const addTableFormData = ref<addTableForm>({})
let searchList: Array<any> = []
const addTableFormRef = ref<FormInstance>()
const selecttipleTableRef = ref()
const datasourceVisible = ref(false)
const userRules = useFormRules([
  {
    key: 'projectName',
    required: true,
    trigger: 'blur',
    msg: '请输入工程名称'
  },
  {
    key: 'projectPackageName',
    required: true,
    trigger: 'blur',
    msg: '请输入工程包名'
  },
  {
    key: 'name',
    required: true,
    trigger: 'blur',
    msg: '请输入功能名称'
  },
  {
    key: 'packageName',
    required: true,
    trigger: 'blur',
    msg: '请输入功能包名'
  },
  {
    key: 'groupId',
    required: true,
    trigger: 'blur',
    msg: '请输入手机号'
  },
  {
    key: 'datasourceId',
    required: true,
    trigger: 'change',
    msg: '请选择数据连接'
  }
])
if (props.editData) {
  projectForm.value = _.cloneDeep(props.editData as typeof formKey)
  dataBase.value = props.editData.moduleTables.map((item: any) => {
    if (item.type === 'PRIMARY')
      item.isPrimary = true
    else item.isPrimary = false
    return { ...item }
  })
}
const addTableRules = useFormRules([
  {
    key: 'tableName',
    required: true,
    trigger: 'blur',
    msg: '请输入表名'
  }
])
// 删除
const handDelete = (row: any, index: any) => {
  msgBoxWarning('确认删除', '确认删除此表吗?', async () => {
    dataBase.value.splice(index, 1)
  })
}

const queryDataBase = async () => {
  const { success, data } = await allDatasource()
  if (success)
    datasourceList.value = data
}
queryDataBase()
// const handleSelectionChange = (val: any) => {
//   multipleSelection.value = val
//   for (let i = 0; i < val.length; i++) {
//     const data = dataBase.value.find(e => e.tableName === val[i].tableName)
//     if (!data) {
//       dataBase.value.push({
//         ...val[i]
//       })
//     }
//   }
// }
const toggleSelection = () => {
  if (dataBase.value.length > 0) {
    dataBase.value.forEach(row => {
      nextTick(() => {
        selecttipleTableRef.value?.toggleRowSelection(row, true)
      })
    })
  }
}
const handleSelect = (selection: any, row: any) => {
  const data = selection.find((e: any) => e.tableName === row.tableName)
  if (!data) {
    dataBase.value.forEach((ele, index) => {
      if (ele.tableName === row.tableName)
        dataBase.value.splice(index, 1)
    })
  }
  else {
    const base = dataBase.value.find(e => e.tableName === row.tableName)
    if (!base) {
      if (dataBase.value.length === 0) {
        dataBase.value.push({
          ...row,
          isPrimary: true
        })
      }
      else {
        dataBase.value.push({
          ...row
        })
      }
    }
  }
}
const addDataBaseTable = async () => {
  if (!projectForm.value.datasourceId) {
    msgError('请先选择数据连接')
    return
  }
  const { success, data } = await addTableDefinition(
    projectForm.value.datasourceId
  )
  if (success) {
    toggleSelection()
    selectVisible.value = true
    selectTable.value = data.map((item: any) => {
      return {
        ...item,
        newTable: false,
        isPrimary: false,
        type: 'ASSOCIATION',
        fields: []
      }
    })
    searchList = selectTable.value
  }
}
const handClosed = () => {
  selectVisible.value = false
}
const handAddClosed = () => {
  addTableFormData.value = {}
  addTableVisible.value = false
}
const clickSearchTable = () => {
  if (selectTableStr.value) {
    selectTable.value = searchList.filter(
      item => item.tableName?.indexOf(selectTableStr.value) !== -1
    )
  }
  else {
    selectTable.value = searchList
  }
}
const addTableClick = () => {
  addTableVisible.value = true
}

const addTableConfirm = async () => {
  await addTableFormRef?.value?.validate((valid, fields) => {
    if (valid) {
      const data = dataBase.value.find(
        e => e.tableName === addTableFormData.value.tableName
      )
      if (data) {
        msgError('已有相同表名')
        return false
      }
      if (projectForm.value.datasourceType === 'DATABASE') {
        const data = selectTable.value.find(
          e => e.tableName === addTableFormData.value.tableName
        )
        if (data) {
          msgError('数据库已有相同表名，请勿重复添加')
          return false
        }
      }

      if (dataBase.value.length === 0) {
        dataBase.value.push({
          ...addTableFormData.value,
          newTable: true,
          fields: [],
          isPrimary: true,
          type: 'ASSOCIATION'
        })
      }
      else {
        dataBase.value.push({
          ...addTableFormData.value,
          newTable: true,
          fields: [],
          isPrimary: false,
          type: 'ASSOCIATION'
        })
      }
      addTableVisible.value = false
      addTableFormData.value = {}
    }
    else {
      console.info('error submit!', fields)
    }
  })
}
const beforeChange = (row: any): Promise<any> => {
  const data = dataBase.value.find(e => e.isPrimary === true)
  return new Promise((resolve, reject) => {
    if (data && data.tableName !== row.tableName) {
      msgError('只能有一个主表')
      return reject(new Error('只能有一个主表'))
    }
    else {
      return resolve(true)
    }
  })
}
const addFunConfirm = async () => {
  const project = await projectFormRef.value.validate((valid: any) => {
    if (valid)
      return true
    else return false
  })

  if (!project)
    return false

  if (dataBase.value.length === 0) {
    msgError('请添加数据库表')
    return false
  }
  else {
    const data = dataBase.value.find(e => e.isPrimary === true)
    if (!data) {
      msgError('请选择数据库主表')
      return false
    }
  }
  const params = {
    ...projectForm.value,
    moduleTables: dataBase.value
  }
  return params
}
const testClick = async () => {
  datasourceVisible.value = true
}
defineExpose({

  projectFormRef,
  dataBase,
  addFunConfirm
})
watch(
  () => props.visible,
  async bool => {
    if (bool) {
      if (props.editData) {
        projectForm.value = _.cloneDeep(props.editData as typeof formKey)
        if (props.editData && props.editData?.moduleTables) {
          dataBase.value = props.editData?.moduleTables.map((item: any) => {
            if (item.type === 'PRIMARY')
              item.isPrimary = true
            else item.isPrimary = false
            return { ...item }
          })
        }
      }
      if (projectData && projectData.value?.goFun === 'fun') {
        projectForm.value.projectId = projectData.value.projectId
        projectForm.value.projectName = projectData.value.name
        projectForm.value.projectPackageName
          = projectData.value.projectPackageName
      }
    }
    else {
      projectForm.value = {
        name: '',
        packageName: '',
        description: '',
        datasourceType: 'DATABASE',
        datasourceId: '',
        projectName: '',
        projectPackageName: '',
        projectId: ''
      }
      dataBase.value = []
    }
  }
)
</script>

<template>
  <div class="manage-design">
    <el-form
      ref="projectFormRef"
      :model="projectForm"
      :rules="userRules"
      label-width="140px"
    >
      <el-row>
        <el-col :span="24" class="elcolTitle">
          <p class="projectTitle">基本信息</p>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工程名称" prop="projectName">
            <el-input
              v-model.trim="projectForm.projectName"
              clearable
              :maxlength="lenName"
              show-word-limit
              placeholder="请输入工程名称"
              :disabled="!!props.editData || !!projectData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工程包名" prop="projectPackageName">
            <el-input
              v-model.trim="projectForm.projectPackageName"
              maxlength="11"
              clearable
              show-word-limit
              placeholder="请输入工程包名"
              :disabled="!!props.editData || !!projectData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="功能名称" prop="name">
            <el-input
              v-model.trim="projectForm.name"
              clearable
              :maxlength="lenName"
              show-word-limit
              placeholder="请输入功能名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="功能包名" prop="packageName">
            <el-input
              v-model.trim="projectForm.packageName"
              maxlength="11"
              clearable
              show-word-limit
              placeholder="请输入功能包名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据库连接方式" prop="datasourceType">
            <el-radio-group v-model="projectForm.datasourceType">
              <el-radio-button label="DATABASE">数据库连接</el-radio-button>
              <el-radio-button label="NO_DB">自定义建表</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="projectForm.datasourceType === 'DATABASE'" class="col-cen" :span="12">
          <el-form-item label="数据连接" prop="datasourceId">
            <el-select
              v-model="projectForm.datasourceId"
              placeholder="请选择数据连接"
            >
              <el-option
                v-for="item in datasourceList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button class="col-btn" type="primary" @click="testClick">
              新建数据源
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目描述" prop="description">
            <el-input
              v-model.trim="projectForm.description"
              :maxlength="lenContent"
              show-word-limit
              :rows="2"
              type="textarea"
              placeholder="请输入项目描述"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="24" class="elcolTitle">
        <p class="projectTitle">库表定义</p>
      </el-col>
      <el-col :span="24" class="table-cen">
        <el-table
          ref="projectModelRef"
          key="projectModel"
          :data="dataBase"
          class="dataTable"
        >
          <el-table-column prop="tableName" label="表名" />
          <el-table-column prop="description" label="描述" width="300" />
          <el-table-column prop="type" label="类别">
            <template #default="{ row }">
              <el-switch
                v-model="row.isPrimary"
                class="ml-2"
                inline-prompt
                style="
                  --el-switch-on-color: #409eff;
                  --el-switch-off-color: #ff4949;
                "
                active-text="主表"
                inactive-text="从表"
                :before-change="
                  () => {
                    return beforeChange(row);
                  }
                "
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="{ row, $index }">
              <IkBtnContent :num="7">
                <el-button
                  type="danger"
                  :icon="Delete"
                  text
                  @click="handDelete(row, $index)"
                >
                  {{ t("action.delete") }}
                </el-button>
              </IkBtnContent>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-col v-if="projectForm.datasourceType === 'DATABASE'" :span="12">
            <div class="addTablebtn" @click="addDataBaseTable">
              <CirclePlus style="width: 1em; height: 1em; margin-right: 8px;" />
              <span>选择表</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="addTablebtn" @click="addTableClick">
              <CirclePlus style="width: 1em; height: 1em; margin-right: 8px;" />
              <span
                v-if="projectForm.datasourceType !== 'NO_DB'"
              >创建表</span>
              <span v-if="projectForm.datasourceType === 'NO_DB'">定义表（不添加实际的数据库表）</span>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog
      v-model="
        selectVisible"
      title="数据选择"
      width="800"
      align-center
      :close-on-click-modal="false"
      @closed="handClosed"
    >
      <el-row class="elcolcen">
        <el-col :span="24" class="elcolTitle">
          <el-input
            v-model.trim="selectTableStr"
            class="m-2 w-50"
            placeholder="请输入关键字"
            clearable
            @clear="clickSearchTable"
          >
            <template #append>
              <el-button :icon="Search" @click="clickSearchTable" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="24" class="elcol">
          <el-table
            key="selectTableModel"
            ref="selecttipleTableRef"
            :data="selectTable"
            class="selectTable"
            height="500"
            current-row-key="tableName"
            @select="handleSelect"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="100" label="序号" />
            <el-table-column prop="tableName" label="表名" />
            <el-table-column prop="description" label="描述" />
          </el-table>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selectVisible = false">取消</el-button>
          <el-button type="primary" @click="selectVisible = false">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="addTableVisible"
      title="添加表"
      width="600px"
      draggable
      align-center
      :close-on-click-modal="false"
      @closed="handAddClosed"
    >
      <el-form
        ref="addTableFormRef"
        :model="addTableFormData"
        :rules="addTableRules"
        label-width="90px"
      >
        <el-row class="elcol">
          <el-col :span="24">
            <el-form-item label="表名" prop="tableName">
              <el-input
                v-model.trim="addTableFormData.tableName"
                clearable
                :maxlength="lenName"
                show-word-limit
                placeholder="请输入表名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model.trim="addTableFormData.description"
                :maxlength="lenContent"
                show-word-limit
                :rows="2"
                type="textarea"
                placeholder="请输入描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTableVisible = false">取消</el-button>
          <el-button type="primary" @click="addTableConfirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <DatasourceModal
      v-model:visible="datasourceVisible"
      @dataChange="queryDataBase"
    />
  </div>
</template>

<style lang="scss" scoped>
.manage-design {
  padding: 15px;
  background-color: var(--color-background);

  .elcolTitle {
    padding: 15px;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 15px;

    .projectTitle {
      font-size: 16px;
      font-weight: 400;
      color: #333;
      padding-left: 10px;
      border-left: 5px solid #409eff;
    }
  }

  .col-cen{
    :deep(.el-form-item__content){
      flex-wrap: nowrap !important;
    }

    .col-btn{
      margin-left: 10px;
    }
  }

  .table-cen{
    min-height: 300px;
  }

  .elcol {
    padding: 15px;
    margin-bottom: 15px;
  }

  .elcolcen {
    overflow: hidden;
  }

  .dataTable {
    padding: 15px;
  }

  .addTablebtn {
    margin: 0 20px;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed #e5e5e5;
  }

  .ml15{
    margin-left: 15px;
  }
}
</style>
